import {
  Breadcrumb,
  Card,
  Form,
  Radio,
  DatePicker,
  Button,
  Table,
  Tag,
  Space,
  Modal,
  message,
} from 'antd';
import { useEffect, useRef, useState } from 'react';
import { Link } from 'react-router-dom';
import './index.scss';
import Cannels from 'components/Cannels';
import { delArticlebyidAPI, getArticleListAPI } from 'api/article';
import defaultImgSrc from 'assets/error.png';
import { EditOutlined, DeleteOutlined } from '@ant-design/icons';
const { RangePicker } = DatePicker;

export default function ArticleList(props) {
  const formDataRef = useRef();
  const pageRef = useRef({});
  // 状态列表渲染
  const articleStatus = [
    { id: -1, name: '全部', color: 'magenta' },
    { id: 0, name: '草稿', color: 'orange' },
    { id: 1, name: '待审核', color: 'red' },
    { id: 2, name: '审核通过', color: 'green' },
    { id: 3, name: '审核失败', color: 'cyan' },
  ];
  const onFinish = (values) => {
    console.log(values);
    let formDate = { ...values };
    // 如果status为-1(全部),则删除
    if (formDate.status === -1) {
      delete formDate.status;
      console.log(formDate);
    }
    // 如果选择日期,转换键名
    if (formDate.data) {
      const begin_pubdate = formDate.data[0]
        .startOf('day')
        .format('YYYY-MM-DD HH:dd:ss');
      const end_pubdate = formDate.data[1]
        .endOf('day')
        .format('YYYY-MM-DD HH:dd:ss');
      formDate.begin_pubdate = begin_pubdate;
      formDate.end_pubdate = end_pubdate;
      delete formDate.data;
      console.log(formDate);
    }
    formDataRef.current = formDate;
    loadArticleList(formDate);
    console.log('formData  ----->  ', formDate);
  };

  // 2. 定义状态准备保存数据，💥 有分页信息以及文章列表
  const [articleData, setArticleData] = useState({});
  // 3. 定义异步方法，请求文章列表的异步方法
  const loadArticleList = async (params) => {
    const res = await getArticleListAPI(params);
    setArticleData(res.data);
    // console.log(articleData);
  };
  const delArticlebyid = async (id) => {
    Modal.confirm({
      title: '温馨提示',
      content: '你确定要删除这篇文章？',
      // 2. onOk表示点击确定时触发， 💥注意async的位置
      onOk: async () => {
        await delArticlebyidAPI(id);
        message.success('删除成功', 1);
        const formData = formDataRef.current || {};
        // 注意带上分页的数据上去
        loadArticleList({ ...formData, ...pageRef.current });
      },
    });
  };
  // 挂载后发请求
  useEffect(() => {
    loadArticleList();
  }, []);
  // 用来指定表格的列如何显示
  const columns = [
    {
      // title控制表头显示内容
      title: '封面',
      // dataIndex代表从数据中取出哪个字段来显示
      //  key的作用是指明不同的列，有不同的key。类似列表渲染
      //  如果有dataIndex时，dataIndex会自动做为key的值，因此可以省略key
      dataIndex: 'cover',
      // render是自定义渲染方法，value是指每一行对应字段的数据
      render: (value) => {
        // console.log('value  ----->  ', value);
        return value.images.length ? (
          <img src={value.images[0]} alt="" width={100} height={60} />
        ) : (
          <img src={defaultImgSrc} alt="" width={100} height={60} />
        );
      },
    },

    {
      title: '标题',
      dataIndex: 'title',
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: (value) => {
        // console.log(value);
        const currentItem = articleStatus.find((item) => item.id === value);
        return <Tag color={currentItem.color}>{currentItem.name}</Tag>;
      },
    },
    {
      title: '发布时间',
      dataIndex: 'pubdate',
    },
    {
      title: '阅读数',
      dataIndex: 'read_count',
    },
    {
      title: '评论数',
      dataIndex: 'comment_count',
    },
    {
      title: '点赞数',
      dataIndex: 'like_count',
    },
    {
      title: '操作',
      key: 'action',
      render: (value, record) => {
        return (
          <Space>
            <Button
              type="primary"
              shape="circle"
              onClick={() => props.history.push(`/edit/${record.id}`)}
              icon={<EditOutlined />}
            ></Button>
            <Button
              shape="circle"
              onClick={() => delArticlebyid(record.id)}
              danger
              icon={<DeleteOutlined />}
            ></Button>
          </Space>
        );
      },
    },
  ];
  // 分页重新发请求
  const handlesetpage = (page, per_page) => {
    // console.log(page, per_page);
    const formData = formDataRef.current || {};
    pageRef.current = { page, per_page };
    loadArticleList({ page, per_page, ...formData });
  };
  return (
    <div className="site-card-border-less-wrapper">
      <Card
        title={
          <Breadcrumb>
            <Breadcrumb.Item>
              <Link to="/home">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>文章列表</Breadcrumb.Item>
          </Breadcrumb>
        }
        bordered={false}
      >
        <Form onFinish={onFinish} autoComplete="off">
          <Form.Item label="状态" name="status">
            <Radio.Group>
              <Radio value={-1}>全部</Radio>
              <Radio value={0}>草稿</Radio>
              <Radio value={1}>待审核</Radio>
              <Radio value={2}>发布通过</Radio>
              <Radio value={3}>发布失败</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item label="频道" name="channel_id">
            <Cannels></Cannels>
          </Form.Item>
          <Form.Item label="日期" name="data">
            <RangePicker />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">
              筛选
            </Button>
          </Form.Item>
        </Form>
        <p>根据筛选条件共查询到 {articleData.total_count} 条结果：</p>
        <Table
          columns={columns}
          dataSource={articleData.results}
          rowKey="id"
          pagination={{
            onChange: handlesetpage,
            position: ['bottomCenter'],
            current: articleData.page,
            total: articleData.total_count,
            pageSize: articleData.per_page,
          }}
        />
      </Card>
    </div>
  );
}
